package com.nail.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.alibaba.fastjson.JSONObject;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.utils.Result4API;

public class LoginFilter implements Filter{
	
	private static final Log logger = LogFactory.getLog(LoginFilter.class);

	private RedisClient redisClient;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setContentType("application/json;charset=UTF-8");

        Result4API result = new Result4API();
        try {
            String token = req.getParameter("token");
            Object user = redisClient.get(Constant.REDIS_USER_KEY + token);
            if(user != null){
                //成功 
                result.setCode(Constant.API_CODE_SUCCESS);
                result.setMsg(Constant.API_MSG_SUCCESS);
                resp.getWriter().write(JSONObject.toJSONString(result));
            }else{
                //用户未登录
                result.setCode(Constant.API_CODE_ERROR);
                result.setMsg(Constant.API_MSG_ERROR);
                resp.getWriter().write(JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            //调用异常
            logger.error(e.toString());
            result.setCode(Constant.API_CODE_501);
            result.setMsg(Constant.API_MSG_ERROR);
            resp.getWriter().write(JSONObject.toJSONString(result));
        }

    }
	
	
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {	
		ServletContext servletContext = filterConfig.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		redisClient = (RedisClient)ctx.getBean("redisClient");
		//System.out.println("注入bean");
	}
	

}
